<?php

namespace app\api\controller\shop;


use addons\epay\library\Service;
use app\admin\model\Cmdlog;
use app\admin\model\Devicelock;
use app\admin\model\money\Platform;
use app\admin\model\Org;
use app\admin\model\Roomclean;
use app\admin\model\Shop;
use app\admin\model\Shopbalanceprofit;
use app\admin\model\Shopdevice;
use app\admin\model\Shopmno;
use app\admin\model\Shopmtdyprofit;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoproombook;
use app\admin\model\Shoptuan;
use app\admin\model\Userallbalance;
use app\admin\model\Userbalance;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\api\service\DeviceService;
use app\api\service\LockService;
use app\api\service\VbillService;
use app\common\controller\Api;
use Exception;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use Yansongda\Pay\Pay;

/**
 *
 */
class Order extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];


    public function getList()
    {

        $shop_id = $this->request->param('shop_id');
        $shopOrderModel = new Shoporder();
        $page = $this->request->param('page');
        $status = $this->request->param('status');
        $orderNo = $this->request->param('orderNo');
        $startTime = $this->request->param('startTime');

        $limit = 10;
        $offset = ($page - 1) * $limit;

        $where = array();
        $where['shop_id'] = $shop_id;
        if ($status != '') {
            $where['Shoporder.status'] = array('=', $status);
        }
        if ($orderNo != "") {
            if (strlen($orderNo) == 11) {
                $userModel = new \app\admin\model\User();
                $user = $userModel->where('mobile', $orderNo)->find();
                if ($user) {
                    $where['Shoporder.user_id'] = $user['id'];
                }
            } else {
                $where['order_no'] = array('like', "%" . $orderNo . "%");
            }
        }
        if ($startTime != "" && $startTime != "时间选择") {
            $start = strtotime($startTime . " 00:00");
            $end = strtotime($startTime . " 23:59");
            $where['create_time'] = array("between", array($start, $end));
        }
        error_log("===where==" . json_encode($where));
        $list = $shopOrderModel->with(['user', 'shop'])->where('Shoporder.status', "<>", 'paying')->where($where)->order('create_time', 'desc')->limit($offset, $limit)->select();
        foreach ($list as $key => $val) {

            $val['user']->hidden(['password', 'salt']);
            $list[$key]['order_no_str'] = substr($val['order_no'], 0, 5) . "*****" . substr($val['order_no'], strlen($val['order_no']) - 4, 4);

            $list[$key]['book_start'] = date("Y-m-d H:i:s", $val['book_start']);
            $list[$key]['book_end'] = date("Y-m-d H:i:s", $val['book_end']);
            $list[$key]['status_txt'] = $shopOrderModel->formatStatus($val['status']);
        }
        $this->success('', $list);
    }


    public function detail()
    {
        $order_no = $this->request->param("order_no");

        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->with(['user'])->where('order_no', $order_no)->find();

        $shopModel = new Shop();
        $shopInfo = $shopModel->where('id', $order['shop_id'])->find();

        $order['profit'] = 0.00;
        if ($order['pay_amount'] > 0) {
            $profitModel = new Shoporderprofit();
            $where = array();
            $where['type'] = 'order';
            $where['from'] = 'qp';

            $orderProfit = $profitModel->where('order_id', $order['id'])->where($where)->find();
            if ($orderProfit) {
                $order['profit'] = $orderProfit['amount'];
            }
        }

        if($order['status'] == 'refund'){
            if($order['profit'] > 0){//用户主动退款后，扣留15%
                $newAmount = formatMoney($order['profit'] * 100 / (100 - $shopInfo['pay_rate'] - $shopInfo['ratio']));//反向计算新金额
                $order['pay_rate'] = formatMoney($newAmount * $shopInfo['pay_rate'] / 100);//店铺支付通道费
                $order['platform_profit'] = max(0.00, formatMoney($newAmount - $order['profit'] - $order['pay_rate']));//平台抽成
            }else{
                $order['pay_rate'] = 0.00;
                $order['platform_profit'] = 0.00;
            }
        }else{
            $order['pay_rate'] = formatMoney($order['pay_amount'] * $shopInfo['pay_rate'] / 100);//店铺支付通道费
            $order['platform_profit'] = max(0.00, formatMoney($order['pay_amount'] - $order['profit'] - $order['pay_rate']));//平台抽成
        }

        $order['tuan'] = "";
        if ($order['tuan_id'] != -1) {
            $userTuanModel = new Usertuan();
            $userTuan = $userTuanModel->where('id', $order['tuan_id'])->find();
            $shopTuanModel = new Shoptuan();
            $tuan = $shopTuanModel->where('id', $userTuan['tuan_id'])->find();
            if ($tuan) {
                $order['tuan'] = $tuan['name'];
            }
        }

        $shopModel = new \app\admin\model\Shop();
        $shopInfo = $shopModel->where('id', $order['shop_id'])->find();
        $order['take_out'] = 0;
        if ($order['status'] != 'refund') {
            if ($shopInfo['is_all'] == 1 || $shopInfo['profit_type'] == 2) {
                if ($order['mt_code'] != "" || $order['dou_code'] != "") {
                    //查询美团抖音的需扣除余额的值
                    $shopMtDyModel = new Shopmtdyprofit();
                    $mtDouProfit = $shopMtDyModel->where('order_id', $order['id'])->find();
                    if (!empty($mtDouProfit)) {
                        $order['take_out'] = $mtDouProfit['profit'];
                    }
                }
            }
        }

        if ($order['take_out'] > 0) {
            $order['mark'] = '全平台扣点订单，需扣除可提现余额 ' . $order['take_out'] . '元';
        }

        $order['user']->hidden(['password', 'salt']);

        $order['status_txt'] = $shopOrderModel->formatStatus($order['status']);
        $order['book_start'] = date("Y-m-d H:i:s", $order['book_start']);
        $order['book_end'] = date("Y-m-d H:i:s", $order['book_end']);
        $this->success('', $order);
    }

    //管理端退款

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws Exception
     */
    public function refund()
    {

        $order_no = $this->request->param('order_no');
        $amount = $this->request->param('amount');
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no', $order_no)->find();

        if ($order['status'] == 'refund') $this->error('该订单已退款');
        if ($order['status'] == 'doing') $this->error('请先结束该订单，然后退款');

        $user = $this->auth->getUser();
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $order['shop_id'])->find();
        if ($shop['user_id'] != $user['id']) {
            $this->error("您没有权限操作退款");
        }

        //退实付
        $this->orderPayRefund($order, $shop, $amount);

        //退余额
        if ($order['balance'] > 0) {
            $userBalanceModel = new Userbalance();
            $where['user_id'] = $order['user_id'];
            $where['order_id'] = $order['id'];
            $where['type'] = 'out';
            $where['from'] = 'qp';

            $userBalanceModel->where($where)->delete();

            //删除平台支出余额
            $userAllBalance = new Userallbalance();
            $userAllBalance->where('order_id', $order['id'])->where('type', 'out')->delete();

            //删除平台商家收益
            $shopBalanceProfit = new Shopbalanceprofit();
            $shopBalanceProfit->where('order_id', $order['id'])->where('order_type', 'qp')->delete();
        }

        //团购券
        if ($order['tuan_id'] != -1) {
            $userTuanModel = new Usertuan();
            $userTuanModel->where('order_id', $order['id'])->update(['status' => 'unuse']);
        }

        //恢复预定
        $roomBookOrderModel = new Shoproombook();
        $roomBookOrderModel->where('order_id', $order['id'])->delete();

        $cleanRoomModel = new Roomclean();
        $cleanRoomModel->where('order_id', $order['id'])->delete();

        $this->success('退款成功');
    }

    public function updateOrderBookTime()
    {

        $order_no = $this->request->param('order_no');
        $time = $this->request->param('time');
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no', $order_no)->find();
        if ($order['status'] != 'payed') {
            $this->error("此订单已开始或者已完成，不支持更改");
        }

        $hour = ($order['book_end'] - $order['book_start']) / 3600;

        $time1 = strtotime($time);
        if ($time1 <= time()) {
            $this->error("选择开始时间 要大于现在的时间");
        }

        $min = $hour * 60 + 30;//也包含保洁的时间
        $min2 = $hour * 60;
        $time2 = strtotime("+" . $min . " minute", $time1);
        $bookEnd = strtotime("+" . $min2 . " minute", $time1);

        $cleanStart = strtotime("+30 minute", $bookEnd);


        $shopRoomBookModel = new Shoproombook();
        $checkStart = $shopRoomBookModel->where('order_id', "<>", $order['id'])->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', "<=", $time1)->where("end_time", ">=", $time1)->find();
        $checkEnd = $shopRoomBookModel->where('order_id', "<>", $order['id'])->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', "<=", $time2)->where("end_time", ">=", $time2)->find();
        $checkEnd3 = $shopRoomBookModel->where('order_id', "<>", $order['id'])->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', ">=", $time1)->where("end_time", "<=", $time2)->find();

        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null) {

            $this->error("此时间段已预定，不能更改订单时间");
        }

        $shopCleanModel = new Roomclean();
        $shopOrderModel->where('id', $order['id'])->update(['book_start' => $time1, 'book_end' => $bookEnd]);
        $shopRoomBookModel->where('order_id', $order['id'])->update(['start_time' => $time1, 'end_time' => $bookEnd]);
        $shopCleanModel->where('order_id', $order['id'])->update(['start_time' => $bookEnd, 'end_time' => $cleanStart]);

        $this->success('成功');
    }

    /**
     * 赠送时间
     */
    public function sendOrderTime2()
    {

        $user = $this->auth->getUser();
        $order_no = $this->request->param('order_no');
        $hour = $this->request->param('hour');
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no', $order_no)->find();
        if ($order['status'] == 'done') {
            $this->error("此订单已结束，不支持续时");
        }


        $time1 = $order['book_end'];
        $min = $hour * 60 + 30;//也包含保洁的时间
        $min2 = $hour * 60;
        $time2 = strtotime("+" . $min . " minute", $time1);
        $bookEnd = strtotime("+" . $min2 . " minute", $time1);

        $cleanStart = strtotime("+30 minute", $bookEnd);


        $shopRoomBookModel = new Shoproombook();
        $checkStart = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', "<", $time1)->where("end_time", ">", $time1)->find();
        $checkEnd = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', "<", $time2)->where("end_time", ">", $time2)->find();
        $checkEnd3 = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', ">", $time1)->where("end_time", "<", $time2)->find();

        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null) {

            $this->error("此时间段已预定，不能续费时间");
        }


//        $checkStart = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', "<=", $time1)->where("end_time", ">=", $time2)->find();
//        $checkEnd = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', ">=", $time1)->where('start_time', "<=", $time2)->where("end_time", ">=", $time2)->find();
//        $checkEnd3 = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', "<=", $time1)->where("end_time", ">=", $time1)->where("end_time", "<=", $time2)->find();
//        $checkEnd4 = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $order['room_id'])->where('start_time', ">=", $time1)->where("end_time", "<=", $time2)->find();
//
//
//        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null || $checkEnd4 != null) {
//            $this->error("此时间段已被预定");
//        }
//
        $shopRoomBookModel = new Shoproombook();
        $roomBook = $shopRoomBookModel->where('order_id', $order['id'])->find();

        $shopCleanModel = new Roomclean();
        $shopOrderModel->where('id', $order['id'])->update(['book_end' => $bookEnd]);
        $shopRoomBookModel->where('order_id', $order['id'])->update(['end_time' => $bookEnd]);
        $shopCleanModel->where('order_id', $order['id'])->update(['start_time' => $bookEnd, 'end_time' => $cleanStart]);

        if ($roomBook['start_time'] > time() && $roomBook['status'] == 'undo') {


            $this->success('');
        }


        if ($roomBook['status'] == 'doing' || $roomBook['status'] == 'undo') {


            if ($roomBook['status'] == 'undo') {
                $shopRoomBookModel->where('id', $roomBook['id'])->update(['status' => 'doing']);
            }
            $minute = floor(($bookEnd - time()) % 86400 / 60);

            //自动发送cmd 续费指令
            $shopDeviceModel = new Shopdevice();

            $newOrderNo = getOrderSn();
            $shopOrderModel->where('id', $order['id'])->update(['order_no' => $newOrderNo]);

            $device = $shopDeviceModel->where('room_id', $order['room_id'])->find();
            $sn = $device['sn'];

            $req = array();
            $req['sec'] = $minute * 60;
            $req['orderNo'] = $newOrderNo;
            $req['sn'] = $sn;
            $req['voice'] = "";


            if ($device['prod'] == 1) {

                if ($device['version'] == 1) {
                    $req = array();
                    $req['sec'] = $minute * 60;
                    $req['orderNo'] = $newOrderNo;
                    $req['sn'] = $sn;
                    $req['voice'] = "";
                    $ret = http_post_json($this->openCmdUrl, json_encode($req));
                    $ret = json_decode($ret, true);
                    if ($ret['code'] == 0) {
                        $msg = "正在打开中";
                    }
                } else {
                    $req = array();
                    $req['sec'] = $minute * 60;
                    $req['orderId'] = $order['id'];
                    $req['deviceSn'] = $device['device_sn'];
                    $ret = http_post_json($this->openV3CmdUrl, json_encode($req));
                    $ret = json_decode($ret, true);
                    if ($ret['code'] == 0) {
                        $msg = "正在打开中";
                    }
                }


                $shopRoomModel = new Shoproom();
                $shopRoomModel->where('id', $order['room_id'])->update(['status' => 'busy']);

                $roomBookModel = new Shoproombook();
                $roomBookModel->where('order_id', $order['id'])->update(['status' => 'doing']);
                $shopOrderModel->where('id', $order['id'])->update(['status' => 'doing']);

                $roomCleanModel = new Shoproom();
                $roomCleanModel->where('id', $order['room_id'])->update(['is_clean' => 1]);

//                $ret = http_post_json($this->openCmdUrl, json_encode($req));
//                $ret = json_decode($ret, true);
            } else {
                $deviceService = new DeviceService();
                $doorReq = array();
                $doorReq['open'] = 1;
                $doorReq['open2'] = 1;
                $doorReq['open3'] = 1;
                $doorReq['open4'] = 1;
                $doorReq['device_sn'] = $device['device_sn'];

                $timeReq = array();
                $timeReq['device_sn'] = $device['device_sn'];
                $timeReq['sec'] = $minute * 60;
                $timeReq['time'] = time();
                $deviceService->dxIotDoor($doorReq);
                $deviceService->dxIotTime($timeReq);
                $ret = array();
            }


            // error_log("=====send====".json_encode($req));
            $cmdModel = new Cmdlog();
            $cmdModel->insert(['user_id' => $user['id'], 'cmd' => json_encode($req),
                'create_time' => time(), 'order_no' => $newOrderNo, 'shop_id' => $order['shop_id'], 'room_id' => $order['room_id']]);
            $this->success('成功', $ret);

        } else {
            $this->error("此订单不是进行中订单，不可续时");
        }


    }

    //需要考虑送时间同时是否存在用户正在预定
    public function sendOrderTime()
    {

        $user = $this->auth->getUser();
        $order_no = $this->request->param('order_no');
        $hour = $this->request->param('hour');
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no', $order_no)->find();
        if ($order['status'] == 'done') {
            $this->error("此订单已结束，不支持续时");
        }

        $time1 = $order['book_end'];
        $min = $hour * 60 + 30;//也包含保洁的时间
        $min2 = $hour * 60;
        $time2 = strtotime("+" . $min . " minute", $time1);
        $bookEnd = strtotime("+" . $min2 . " minute", $time1);

        $cleanStart = strtotime("+30 minute", $bookEnd);

        //判断是否再续时的同时有人在预定
        $cacheKey = "room_" . $order['room_id'];
        $cache = $this->redis->get($cacheKey);
        if ($cache) {
            $cacheObj = $this->redis->get($cacheKey);
            $checkMowTime = strtotime("-60 seconds", time());
            $cache = json_decode($cacheObj, true);
            if ($cache['create_time'] < $checkMowTime) {
                $this->redis->rm($cacheKey);
            }

            $start = $cache['start'];
            $end = $cache['end'];
            if ($cache['user_id'] != $user['id']) {
                if (!$this->isOverLap($time1, $time2, $start, $end)) {
                    $this->error("请稍后提交，前面有客户正在预定");
                }
            }
        }
        $cacheObj = array();
        $cacheObj['user_id'] = $user['id'];
        $cacheObj['start'] = $time1;
        $cacheObj['end'] = $time2;
        $cacheObj['create_time'] = time();
        $this->redis->set($cacheKey, json_encode($cacheObj));

        $shopRoomBookModel = new Shoproombook();
        $bookList = $shopRoomBookModel->where('room_id', $order['room_id'])->where('status', 'in', ['undo', 'doing'])->order('start_time', 'desc')->select();
        foreach ($bookList as $key => $val) {

            $start = $val['start_time'];
            $end = $val['end_time'];
            if (!$this->isOverLap($time1, $time2, $start, $end)) {
                $this->error("此时间段已被预定");
            }
        }
        $roomBook = $shopRoomBookModel->where('order_id', $order['id'])->find();

        $shopCleanModel = new Roomclean();
        $shopOrderModel->where('id', $order['id'])->update(['book_end' => $bookEnd]);
        $shopRoomBookModel->where('order_id', $order['id'])->update(['end_time' => $bookEnd]);
        $shopCleanModel->where('order_id', $order['id'])->update(['start_time' => $bookEnd, 'end_time' => $cleanStart]);

        if ($roomBook['start_time'] > time() && $roomBook['status'] == 'undo') {
            $this->success('');
        }

        if ($roomBook['status'] == 'doing' || $roomBook['status'] == 'undo') {

            if ($roomBook['status'] == 'undo') {
                $shopRoomBookModel->where('id', $roomBook['id'])->update(['status' => 'doing']);
            }
            $minute = floor(($bookEnd - time()) % 86400 / 60);

            //自动发送cmd 续费指令
            $newOrderNo = getOrderSn();
            $shopOrderModel->where('id', $order['id'])->update(['order_no' => $newOrderNo]);

            $shopDeviceModel = new Shopdevice();
            $device = $shopDeviceModel->where('room_id', $order['room_id'])->find();
            $sn = $device['sn'];

            $req = array();
            $req['sec'] = $minute * 60;
            $req['orderNo'] = $newOrderNo;
            $req['sn'] = $sn;
            $req['voice'] = "";

            if ($device['prod'] == 1) {

                if ($device['version'] == 1) {
                    $req = array();
                    $req['sec'] = $minute * 60;
                    $req['orderNo'] = $newOrderNo;
                    $req['sn'] = $sn;
                    $req['voice'] = "";
                    $ret = http_post_json($this->openCmdUrl, json_encode($req));
                    $ret = json_decode($ret, true);
                    if ($ret['code'] == 0) {
                        $msg = "正在打开中";
                    }
                } else {
                    $req = array();
                    $req['sec'] = $minute * 60;
                    $req['orderId'] = $order['id'];
                    $req['deviceSn'] = $device['device_sn'];
                    $ret = http_post_json($this->openV3CmdUrl, json_encode($req));
                    $ret = json_decode($ret, true);
                    if ($ret['code'] == 0) {
                        $msg = "正在打开中";
                    }
                }

                $shopRoomModel = new Shoproom();
                $shopRoomModel->where('id', $order['room_id'])->update(['status' => 'busy']);

                $roomBookModel = new Shoproombook();
                $roomBookModel->where('order_id', $order['id'])->update(['status' => 'doing']);
                $shopOrderModel->where('id', $order['id'])->update(['status' => 'doing']);

                $roomCleanModel = new Shoproom();
                $roomCleanModel->where('id', $order['room_id'])->update(['is_clean' => 1]);

//                $ret = http_post_json($this->openCmdUrl, json_encode($req));
//                $ret = json_decode($ret, true);
            } else {
                $deviceService = new DeviceService();
                $doorReq = array();
                $doorReq['open'] = 1;
                $doorReq['open2'] = 1;
                $doorReq['open3'] = 1;
                $doorReq['open4'] = 1;
                $doorReq['device_sn'] = $device['device_sn'];

                $timeReq = array();
                $timeReq['device_sn'] = $device['device_sn'];
                $timeReq['sec'] = $minute * 60;
                $timeReq['time'] = time();
                $deviceService->dxIotDoor($doorReq);
                $deviceService->dxIotTime($timeReq);
                $ret = array();
            }

            // error_log("=====send====".json_encode($req));
            $cmdModel = new Cmdlog();
            $cmdModel->insert(['user_id' => $user['id'], 'cmd' => json_encode($req),
                'create_time' => time(), 'order_no' => $newOrderNo, 'shop_id' => $order['shop_id'], 'room_id' => $order['room_id']]);
            $this->success('成功', $ret);

        } else {
            $this->error("此订单不是进行中订单，不可续时");
        }


    }


    public function setRoom()
    {
        $room_id = $this->request->param('room_id');
        $order_no = $this->request->param('order_no');
        $shopOrderModel = new Shoporder();
        $oldOrder = $shopOrderModel->where('order_no', $order_no)->find();
        if ($oldOrder['status'] == 'done' || $oldOrder['status'] == 'refund') {
            $this->error("此订单已结束，不支持更换");
        }
        if ($room_id == $oldOrder['room_id']) {
            $this->error("此订单包厢 就是该包厢 不支持更换");
        }
        $time1 = $oldOrder['book_start'];
        $time2 = $oldOrder['book_end'];

        $deviceModel = new Shopdevice();
        $oldDevice = $deviceModel->where('room_id', $oldOrder['room_id'])->find();
        $newDevice = $deviceModel->where('room_id', $room_id)->find();
        if (empty($newDevice)) $this->error('该包厢暂未绑定设备');

        $shopRoomBookModel = new Shoproombook();
        $checkStart = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $room_id)->where('start_time', "<", $time1)->where("end_time", ">", $time1)->find();
        $checkEnd = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $room_id)->where('start_time', "<", $time2)->where("end_time", ">", $time2)->find();
        $checkEnd3 = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $room_id)->where('start_time', ">", $time1)->where("end_time", "<", $time2)->find();

        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null) {

            $this->error("此时间段已预定，不能续费时间");
        }

        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id', $room_id)->find();
        $shopOrderModel->where('id', $oldOrder['id'])->update(['room_id' => $room_id, 'room_name' => $room['name']]);
        $shopRoomModel->where('id', $room_id)->update(['status' => 'busy']);
        $shopRoomModel->where('id', $oldOrder['room_id'])->update(['status' => 'free']);

        $shopRoomBookModel = new Shoproombook();
        $shopCleanModel = new Roomclean();
        $shopCleanModel->where('order_id', $oldOrder['id'])->update(['room_id' => $room_id]);
        $shopRoomBookModel->where('order_id', $oldOrder['id'])->update(['room_id' => $room_id]);

        $newOrder = $shopOrderModel->where('order_no', $order_no)->find();

        if ($oldOrder['status'] == 'doing') {
            //先关老包厢，再开新包厢
            $this->closeDevice($oldOrder, $oldDevice);
            $this->openDevice($newOrder, $newDevice);
        }

        $this->success('修改成功');

    }

    //开包箱
    protected function openDevice($order, $device)
    {
        $req = array();
        if ($device['version'] == 1) {

            $req['sec'] = $order['book_end'] - time();
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];
            $req['voice'] = "";
            $ret = http_post_json($this->openCmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
            if ($ret['code'] == 0) {
                $msg = "正在打开中";
            }
        } else {
            $req['sec'] = $order['book_end'] - time();
            $req['orderId'] = $order['id'];
            $req['deviceSn'] = $device['device_sn'];
            $ret = http_post_json($this->openV3CmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
            if ($ret['code'] == 0) {
                $msg = "正在打开中";
            }
        }

        $db = array();
        $db['order_no'] = $order['order_no'];
        $db['shop_id'] = $order['shop_id'];
        $db['room_id'] = $order['room_id'];
        $db['user_id'] = $this->auth->getUser()['id'];
        $db['create_time'] = time();
        $db['cmd'] = json_encode($req);
        $cmdModel = new Cmdlog();
        $cmdModel->insert($db);

        $deviceLockModel = new Devicelock();
        $lock = $deviceLockModel->where('room_id', $device['room_id'])->find();
        if ($lock) {
            if ($lock['is_gateway'] == 1) {
                //网关开锁
                $lockService = new LockService();
                $lockReq = array();
                $lockReq['lockId'] = $lock['lockId'];
                $lockService->openLock($lockReq);

            }
        }

    }

    //关包厢
    protected function closeDevice($order, $device)
    {
        $req = array();
        if ($device['version'] == 1) {

            $req['sec'] = 0;
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];
            $req['voice'] = "";
            $ret = http_post_json($this->openCmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
            if ($ret['code'] == 0) {
                $msg = "正在打开中";
            }
        } else {
            $req['sec'] = 0;
            $req['orderId'] = $order['id'];
            $req['deviceSn'] = $device['device_sn'];
            $ret = http_post_json($this->openV3CmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
            if ($ret['code'] == 0) {
                $msg = "正在打开中";
            }
        }

        $db = array();
        $db['order_no'] = $order['order_no'];
        $db['shop_id'] = $order['shop_id'];
        $db['room_id'] = $order['room_id'];
        $db['user_id'] = $this->auth->getUser()['id'];
        $db['create_time'] = time();
        $db['cmd'] = json_encode($req);
        $cmdModel = new Cmdlog();
        $cmdModel->insert($db);
    }

    //订单实付退款
    protected function orderPayRefund($order, $shop, $amount)
    {

        $shopOrderModel = new Shoporder();
        $refundAmount = 0.00;
        $new_pay_amount = 0.00;
        if ($amount > 0) {
            if ($amount > $order['pay_amount']) $this->error('退款金额不能大于支付金额');
            $new_pay_amount = formatMoney($order['pay_amount'] - $amount);
            $refundAmount = $amount;
        }

        if ($order['pay_amount'] > 0 && $refundAmount > 0) {

            $refundOrder_no = getOrderSn();

            $orgModel = new Org();
            $org = $orgModel->where('id', $order['org_id'])->find();

            $shopMnoModel = new Shopmno();
            $shopMno = $shopMnoModel->where('shop_id', $order['shop_id'])->find();
            $mno = $org['mno'];
            if ($shopMno && $shopMno['ratio'] == 100) {
                $mno = $shopMno['mno'];
            }
            $req = array();
            $req['mno'] = $mno;
            $req['ordNo'] = $refundOrder_no;
            $req['origOrderNo'] = $order['order_no'];
            $req['amt'] = $refundAmount;

            $vbillService = new VbillService();
            $ret = $vbillService->refund($req);
            error_log("==admin=app=refund===" . $ret);
            $result = json_decode($ret, true);

            //判断原订单不一致的问题
            if ($result['code'] != '0000') {
                $this->error($result['msg']);
            }

            if ($result['respData']['bizCode'] != "0000") {
                $this->error($result['respData']['bizMsg']);
            }

            $shopOrderProfitModel = new Shoporderprofit();
            $userOrderProfitModel = new Userorderprofit();
            $platformModel = new Platform();
            if ($new_pay_amount > 0) {

                //部分退款，重新划分商家收益、通道支付费以及平台收益
                $new_pay_rate = formatMoney($new_pay_amount * $shop['pay_rate'] / 100);//支付通道费
                $new_profit = formatMoney($new_pay_amount * (100 - $shop['ratio'] - $shop['pay_rate']) / 100);//商家收益
                $new_rate = formatMoney($new_pay_amount - $new_profit - $new_pay_rate);//平台收益
                $new_amount = formatMoney($order['amount'] - $amount);//新的订单金额
                $shopOrderModel->where('id', $order['id'])->update(['amount' => $new_amount, 'pay_amount' => $new_pay_amount, 'pay_rate' => $new_pay_rate, 'rate' => $new_rate, 'update_time' => time()]);
                $shopOrderProfitModel->where('order_id', $order['id'])->where('shop_id', $order['shop_id'])->where('type', 'order')->where('from', 'qp')->update(['amount' => $new_profit]);

                $new_user_profit = formatMoney($new_pay_amount * $shop['agent_ratio'] / 100);
                $userOrderProfitModel->where('user_id', $shop['agent_id'])->where('order_id', $order['id'])->where('type', ' order')->update(['amount' => $new_user_profit]);
                $platformModel->where('order_id', $order['id'])->where('type', ' order')->where('from', 'qp')->update(['order_pay_amount' => $new_pay_amount, 'shop_amount' => $new_profit, 'rate' => $new_rate, 'agent_rate' => $new_user_profit]);

            } else {
                //全退，修改订单状态、删除收益记录
                $shopOrderModel->where('id', $order['id'])->update(['status' => 'refund', 'update_time' => time()]);//修改订单状态
                $shopOrderProfitModel->where('order_id', $order['id'])->where('shop_id', $order['shop_id'])->where('type', 'order')->where('from', 'qp')->delete();
                $userOrderProfitModel->where('user_id', $shop['agent_id'])->where('order_id', $order['id'])->where('type', ' order')->delete();
                $platformModel->where('order_id', $order['id'])->where('type', ' order')->where('from', 'qp')->delete();

            }

        } else {
            $shopOrderModel->where('id', $order['id'])->update(['status' => 'refund', 'update_time' => time()]);
        }
    }

    //判断时间段是否重叠
    protected function isOverLap($start1, $end1, $start2, $end2): bool
    {
        return $end1 <= $start2 || $start1 >= $end2;
    }

}
